package com.along.service;

import com.along.entity.Dept;
import com.along.entity.DeptES;
import com.along.repository.DeptESRepository;
import com.along.repository.DeptRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
/*
 * @Author: liujinyi
 * @DateTime: 2025/7/4 16:29
 */
@Slf4j
@Service
public class DeptSyncService {
    @Autowired
    private DeptRepository deptRepository;

    @Autowired
    private DeptESRepository deptESRepository;

    @Transactional
    public void save(Dept dept) {
        Date now = new Date();
        dept.setCreateTime(now);
        dept.setUpdateTime(now);
        deptRepository.save(dept);
        log.info("保存到MySQL成功: {}", dept);

        // 同步到ES
        DeptES esDept = new DeptES();
        BeanUtils.copyProperties(dept, esDept);
        deptESRepository.save(esDept);
        log.info("同步到ES成功: {}", esDept);
    }

    public List<DeptES> searchFromEs(String keyword) {
        return deptESRepository.findByDeptNameContaining(keyword);
    }

    public List<Dept> findAllFromMysql() {
        return deptRepository.findAll();
    }
}
